import React, { FC, useEffect, useRef, useState } from "react";
import "./index.css";
import {
  Tabs,
  Table,
  Row,
  Col,
  Button,
  Input,
  Tag,
  Drawer,
  Descriptions,
  message,
  Modal,
} from "antd";
import { useRequest } from "@umijs/hooks";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import { useHistory } from "react-router";
import { SearchOutlined, SyncOutlined } from "@ant-design/icons";
import { getSecretString } from "@/utils/encrypt";

const { TabPane } = Tabs;

const { TextArea } = Input;
const tabsList = [
  { tab: "待审核", type: "2" },
  { tab: "不通过", type: "3" },
  { tab: "已完成", type: "1" },
];

const ReleaseInformation: FC = () => {
  const [value, setValue] = useState("");
  const [search, setSearch] = useState("");
  const [searchID, setSearchID] = useState("0");

  const onSearch = () => {
    setSearch(() => value);
  };

  return (
    <div className={"release-wrap"}>
      <div className="release-wrap-search">
        {/* <div>
                <div>
                    <span>发布人:</span>
                    <Input value={value} onChange={(e) => setValue(e.target.value)} />
                </div>
                <div>
                    <Button type={'primary'} onClick={onSearch} icon={<SearchOutlined />}>搜索</Button>
                    <Button onClick={() => {
                        setValue(() => '');
                        setSearchID('0')
                        onSearch()
                    }} icon={<SyncOutlined />}>重置</Button>
                </div>
            </div> */}
        <Row>
          <Col>
            <div className="flex">
              <span className="spantitle">发布人:</span>
              <Input
                value={value}
                onChange={(e) => setValue(e.target.value)}
                className="inputName"
              />
            </div>
            {/* <Row className={'flex'}>
                        <Col><span>发布人:</span></Col>
                        <Col offset={1}><Input value={value} onChange={(e) => setValue(e.target.value)} /></Col>
                    </Row> */}
          </Col>
          <Col offset={1} className={"btn-wrap"}>
            <Button
              type={"primary"}
              onClick={onSearch}
              icon={<SearchOutlined />}
            >
              搜索
            </Button>
            <Button
              onClick={() => {
                setValue(() => "");
                setSearchID("0");
                onSearch();
              }}
              icon={<SyncOutlined />}
            >
              重置
            </Button>
          </Col>
        </Row>
      </div>
      <Tabs
        onChange={(value) => setSearchID(value)}
        activeKey={searchID}
        className="release-wrap-title"
      >
        {tabsList.map((item, index) => (
          <TabPane tab={item.tab} key={index}>
            <InfoTable
              search={search}
              id={index}
              searchID={searchID}
              type={item.type}
            />
          </TabPane>
        ))}
      </Tabs>
    </div>
  );
};

const InfoTable: FC<{
  search: string;
  id: number;
  searchID: string;
  type: string;
}> = ({ search, id, searchID, type }) => {
  const [visible, setVisible] = useState(false);
  const [col, setCol] = useState<any>({});
  const [isModalVisible, setIsModalVisible] = useState<any>(false);
  const router = useHistory();

  const { tableProps, run } = useRequest(
    (current, params) =>
      fetchRequest(url.GET_INFO, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params,
      }),
    {
      paginated: true,
      manual: true,
      formatResult: (response: any) => {
        return {
          list: response.data?.rows,
          total: response?.data?.total,
          success: response.success,
          errorMsg: response.errorMsg,
        };
      },
    }
  );

  //敏感词信息提醒
  const { run: Resrun, loading } = useRequest(
    (params) => fetchRequest(url.GET_RESULTS, params),
    {
      manual: true,
      onSuccess: async (result, params) => {
        if (!result.success) {
          message.error(result.errorMsg);
          return;
        }
        if (result.success) {
          message.success(result.data);
          const id = setTimeout(() => {
            router.go(0);
            clearTimeout(id);
          }, 500);
        }
      },
    }
  );

  useEffect(() => {
    if (parseInt(searchID) === id) {
      run({ pageSize: 10, current: 1 }, { id: type, name: search });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchID, search]);

  const cols = [
    {
      title: "发布人",
      key: "userName",
      dataIndex: "userName",
    },
    {
      title: "发布模块",
      key: "noticeName",
      dataIndex: "noticeName",
    },
    {
      title: "提交时间",
      key: "createTime",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      render: (col: any) => {
        return (
          <Tag
            color={"rgb(16, 142, 233)"}
            onClick={() => {
              setVisible(true);
              setCol(col);
            }}
          >
            {searchID === "0" ? "操作" : "查看"}
          </Tag>
        );
      },
    },
  ];

  const agree = async (result: any) => {
    if (!result) {
      setIsModalVisible(true);
      return;
    }

    await Resrun({
      noticeId: getSecretString(`${col.noticeId}`),
      phone: col.phone,
      name: col.userName,
      time: col.createTime,
      noticeType: col.noticeType,
      result,
    });
  };

  const remark = useRef<any>(null);
  const handleOk = async () => {
    const remarkValue = remark.current?.resizableTextArea?.props?.value;

    if (!remarkValue) {
      message.error("请输入不通过原因");
      return;
    }

    await Resrun({
      noticeId: getSecretString(`${col.noticeId}`),
      phone: col.phone,
      name: col.userName,
      time: col.createTime,
      noticeType: col.noticeType,
      result: 0,
      remark: remarkValue,
    });
  };

  return (
    <>
      <Table columns={cols} rowKey={"noticeId"} {...(tableProps as any)} />
      <InfoDrawer
        visible={visible}
        onClose={() => setVisible(false)}
        col={col}
        type={type}
      >
        {searchID === "0" ? (
          <div className={"release-information-btn-wrap"}>
            <Button type="primary" loading={loading} onClick={() => agree(1)}>
              通过
            </Button>
            <Button onClick={() => agree(0)} loading={loading}>
              不通过
            </Button>
          </div>
        ) : null}
      </InfoDrawer>

      <Modal
        title="审核原因"
        visible={isModalVisible}
        footer={[
          <Button
            key="submit"
            type="primary"
            loading={loading}
            onClick={handleOk}
          >
            提交
          </Button>,
        ]}
        onCancel={() => setIsModalVisible(false)}
      >
        <Row className={"flex"}>
          <Col span={3}>原因:</Col>
          <Col offset={1} span={20}>
            <TextArea maxLength={50} showCount ref={remark} />
          </Col>
        </Row>
      </Modal>
    </>
  );
};
type InfoDrawerProps = {
  visible: boolean;
  onClose: () => void;
  col: any;
  type: string;
};
const InfoDrawer: FC<React.PropsWithChildren<InfoDrawerProps>> = ({
  visible,
  onClose,
  col,
  children,
  type,
}) => {
  const { tableProps, run } = useRequest(
    (current, params) =>
      fetchRequest(url.GET_AUDITINFO, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params,
      }),
    {
      paginated: true,
      manual: true,
      formatResult: (response: any) => {
        return {
          list: response.data?.rows,
          total: response?.data?.total,
          success: response.success,
          errorMsg: response.errorMsg,
        };
      },
    }
  );

  const keys = [
    { key: "userName", title: "发布人", span: 1 },
    { key: "noticeName", title: "发布类型", span: 1 },
    { key: "phone", title: "发布人电话", span: 1 },
    { key: "createTime", title: "创建时间", span: 1 },
    { key: "deptName", title: "发布对象", span: 2 },
  ];
  if (col.noticeType !== "3") {
    keys.push({ key: "content", title: "发布内容", span: 3 });
  }

  const examineKey = [
    { key: "auditName", title: "审核人", span: 3 },
    { key: "auditAt", title: "审核时间", span: 3 },
  ];
  console.log(`type:${type}`);

  if (type === "3") {
    examineKey.push({ key: "remark", title: "审核不通过原因", span: 3 });
  }

  let columns = [
    {
      title: "学生",
      key: "studentName",
      dataIndex: "studentName",
    },
    {
      title: "通知状态",
      key: "stateName",
      dataIndex: "stateName",
    },
  ];

  if (col.noticeType === "3") {
    columns = [
      ...columns,
      {
        title: "成绩",
        key: "scoreContent",
        dataIndex: "scoreContent",
      },
    ];
  }

  useEffect(() => {
    if (col.noticeId) {
      run(
        { pageSize: 10, current: 1 },
        {
          noticeId: getSecretString(`${col.noticeId}`),
          noticeType: col.noticeType,
        }
      );
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [col.noticeId]);

  return (
    <Drawer
      title="发布信息"
      placement="right"
      closable={false}
      onClose={onClose}
      visible={visible}
      width={1000}
    >
      <Descriptions bordered title={"发布信息"}>
        {keys.map((item: any) => (
          <Descriptions.Item label={item.title} key={item.key} span={item.span}>
            {col[item.key]}
          </Descriptions.Item>
        ))}
      </Descriptions>

      {type === "1" || type === "3" ? (
        <Descriptions bordered title={"审核信息"} className={"score-table"}>
          {examineKey.map((item: any) => (
            <Descriptions.Item
              label={item.title}
              key={item.key}
              span={item.span}
            >
              {col[item.key]}
            </Descriptions.Item>
          ))}
        </Descriptions>
      ) : null}
      <div className={"ant-descriptions-title score-table"}>学生信息</div>
      <Table
        columns={columns}
        style={{ margin: "20px 0", padding: 0 }}
        rowKey={"userId"}
        {...(tableProps as any)}
      />
      {children}
    </Drawer>
  );
};

export default ReleaseInformation;
